<?php

namespace app\index\controller;

use app\common\controller\Front;

class Store extends Front
{

    private $joinInfo = [];

    /**
     * 店铺展示页
     */
    public function index()
    {
        $store_id = $this->request->param('store_id/d', 0);
        $store_info = rpc('common/common/one', [
            'store',
                [
                'id' => $store_id
            ],
                [
                'field' => 'id,name,company_name,slide,slide_url,label'
            ]
        ]);
        if (empty($store_info)) {
            return showMessage('该店铺已关闭', '', '', 'error');
        }
        $search_key = $this->request->param('key/d', 0); // 0默认排序，1销量 ， 2人气 ，3价格
        $search_order = $this->request->param('order/d', 0); // 0是默认无排序，1是低到高，2是高到低
        $search_area_id = $this->request->param('area_id/d', 0); // 默认地区0
        if ($search_area_id) {
            // $area = \Area::get_by_id($search_area_id);
            $area = rpc('common/common/one', [
                'area',
                    [
                    'area_id' => $search_area_id
                ],
                    [
                    'field' => 'area_name'
                ]
            ]);
            if ($area) {
                $search_area = $area['area_name']; // 搜索地区0
            } else {
                $search_area = ''; // 搜索地区
            }
        }
        $search_b_id = $this->request->param('b_id/d', 0); // 品牌ID
        $search_a_id = $this->request->param('a_id/d', 0); // 属性ID
        $search_gift = $this->request->param('gift/d', 0); // 是否有礼物
        $search_type = $this->request->param('type/d', 0); // 是否自营店铺
        $search_spec = $this->request->param('spec/a', []); // 规格查询条件
        $page_size = config('limit_goods_store');
        $page_size = $page_size ?: 24;
        $curpage = $this->request->param('curpage/d', 1); // 当前页，默认第一页
        $tag = $this->request->param('tag/s', ''); // 商品分类标识(点击菜单来携带这个参数)
        $search_classid = $this->request->param('cate_id/s', ''); // 商品分类ID(点击排序或者分页，带这个参数)

        $goods_class_array = config('mall_cate'); // 系统总分类
        // 判断当前分类是一级还是二级
        $one_id = $two_id = 0;
        if (key_exists($search_classid, $goods_class_array))
            $one_id = $search_classid;
        else
            $two_id = $search_classid;
        // 获取店铺商品分类
        $store_gc_class = rpc('common/common/lists', [
            'store_bind_class',
                [
                'store_id' => $store_id,
                'state' => 1,
                'status' => 1,
                'isdelete' => 0
            ],
                [
                'field' => 'store_id,class_1,class_2'
            ]
        ]);
        if (!empty($store_gc_class) && is_array($store_gc_class)) {
            $tmp = [];
            foreach ($store_gc_class as $key => $val) {
                if (isset($goods_class_array[$val['class_1']]) && isset($goods_class_array[$val['class_1']]['_child'][$val['class_2']])) {
                    if (!isset($tmp[$val['class_1']])) {
                        $tmp[$val['class_1']] = [
                            'id' => $val['class_1'],
                            'name' => $goods_class_array[$val['class_1']]['name']
                        ];
                    }
                    $tmp[$val['class_1']]['_child'][$val['class_2']] = [
                        'id' => $val['class_2'],
                        'name' => $goods_class_array[$val['class_1']]['_child'][$val['class_2']]['name']
                    ];
                }
            }
            $store_gc_class = $tmp;
        }

        $where = ' store_id=' . $store_id . ' and goods_verify=1 and goods_state=1';
        // 处理排序
        $order = 'goods_common.id desc';
        if (in_array($search_key, [
                    '1',
                    '2',
                    '3'
                ])) {
            $sequence = $search_order == '1' ? 'asc' : 'desc';
            switch ($search_key) {
                case '1':
                    $order = 'goods_common_static.last_30_salenum';
                    break;
                case '2':
                    $order = 'goods_common_static.click_num';
                    break;
                case '3':
                    $order = 'goods_common.goods_price';
                    break;
            }
            $order .= ' ' . $sequence;
        }
        // 执行正常搜索
        if ($one_id) {
            $where .= ' and gc_id_1=' . $one_id;
        }
        if ($two_id) {
            $where .= ' and gc_id=' . $two_id;
        }
        if ($search_b_id > 0) {
            $where .= ' and brand_id=' . $search_b_id;
        }
        if ($search_type == 1) {
            $where .= ' and is_own_shop=1 ';
        }
        if ($search_gift == 1) {
            $where .= ' and have_gift=1 ';
        }
        if (!empty($search_area)) {
            $tmp_str = !empty($search_area) ? '%' . $search_area . '%' : '';
            $where .= ' and (goods_common.goods_name like "' . $tmp_str . '" or goods_common.goods_jingle like "' . $tmp_str . '" or goods_common.spec_value like "' . $tmp_str . '")';
        }
        // 字段
        $fields = "goods_common.*, goods_common_static.evaluation_scores, goods_common_static.total_salenum, goods_common_static.last_30_salenum, goods_common_static.click_num";

        // 拼接sql串
        $sql = "select " . $fields . " from mall_goods_common goods_common left join mall_goods_common_static goods_common_static on goods_common.id=goods_common_static.commonid where " . $where . " order by " . $order . ' limit ' . ($curpage - 1) * $page_size . ',' . $page_size;
        ;
        $goods_common_list = rpc('common/common/sql', [
            $sql
        ]);
        $sql = "select count(goods_common.id) as num from mall_goods_common goods_common left join mall_goods_common_static goods_common_static on goods_common.id=goods_common_static.commonid where " . $where;
        $total_num = rpc('common/common/sql', [
            $sql
        ]);
        $total_num = $total_num[0]['num'];
        if (!empty($goods_common_list)) {
            // 商品多图
            $commonid_array = array_map('reset', $goods_common_list); // 商品公共id数组
            $storeid_array = array(); // 店铺id数组
            $goodsid_array = array(); // 公共内容的商品代表数组
            $where = " commonid in (" . implode(',', $commonid_array) . ")";
            if (!empty($search_area)) {
                $tmp_str = !empty($search_area) ? '%' . $search_area . '%' : '';
                $where .= ' and (goods_name like "' . $tmp_str . '" or goods_jingle like "' . $tmp_str . '" or goods_spec like "' . $tmp_str . '")';
            }
            $sql = "select id,commonid from mall_goods where " . $where . " group by commonid";
            $goodsid_tmp_array = rpc('common/common/sql', [
                $sql
            ]);
            if (!empty($goodsid_tmp_array)) {
                foreach ($goodsid_tmp_array as $key => $val) {
                    $goodsid_array[$val['commonid']] = $val['id'];
                }
            }
            // 店铺
            if (!empty($goods_common_list)) {
                foreach ($goods_common_list as $key => $val) {
                    $storeid_array[] = $val['store_id'];
                }
            }
            foreach ($goods_common_list as $key => $value) {
                // 添加公共内容的代表商品id
                $goods_common_list[$key]['goods_id'] = isset($goodsid_array[$value['id']]) ? $goodsid_array[$value['id']] : 0;
            }
        }
        $query = [
            'store_id' => $store_id,
            'cate_id' => $search_classid,
            'key' => $search_key,
            'order' => $search_order,
            'area_id' => $search_area_id
        ];
        // 分页渲染内容
        $option = [
            'var_page' => 'curpage',
            'path' => url('index/store/index', $query)
        ];
        $page = \Page::make($goods_common_list, $page_size, $curpage, $total_num, false, $option);
        // 加载当前店铺轮播图
        if ($store_info['slide'] != '' && $store_info['slide'] != ',,,,') {
            $this->view->assign('slide', explode(',', $store_info['slide']));
            $this->view->assign('slide_url', explode(',', $store_info['slide_url']));
        }
        //店铺默认轮播图
        $default_slide = \Fields::getById('store_open');
        // 加载地区
        $list_area = $this->db_lists('area', '', [
            'page' => '1,5000'
        ]);
        $this->view->assign('list_area', json_encode($list_area));
        $this->view->assign('return_area_id', $search_area_id);
        $this->view->assign('search_area_name', $search_area);
        $this->view->assign('store_gc_class', $store_gc_class);
        $this->view->assign('default_classid', $search_classid);
        $this->view->assign('search_key', $search_key);
        $this->view->assign('search_order', $search_order);
        $this->view->assign('store_id', $store_id);
        $this->view->assign('one_id', $one_id);
        $this->view->assign('two_id', $two_id);
        $this->view->assign('page', $page);
        $this->view->assign('goods_common_list', $goods_common_list);
        $this->view->assign('total_num', $total_num);
        $this->view->assign('query', $query);
        $this->view->assign('store_info', $store_info);
        $this->view->assign('default_slide', $default_slide);
        // SEO
        $this->view->assign('_page', [
            'title' => '爱员工官网',
            'name' => $store_info['name']
        ]);
        return view();
    }

    /**
     * 店铺介绍
     */
    public function info()
    {
        $store_id = $this->request->param('store_id/d', 0);
        $store_info = rpc('common/common/one', [
            'store',
                [
                'id' => $store_id
            ],
                [
                'field' => 'id,intro,slide_url,slide'
            ]
        ]);
        if (empty($store_info)) {
            return showMessage('该店铺已关闭', '', '', 'error');
        }
        // 加载当前店铺轮播图
        if ($store_info['slide'] != '' && $store_info['slide'] != ',,,,') {
            $this->view->assign('slide', explode(',', $store_info['slide']));
            $this->view->assign('slide_url', explode(',', $store_info['slide_url']));
        }
        //店铺默认轮播图
        $default_slide = \Fields::getById('store_open');
        $this->view->assign('store_info', $store_info);
        $this->view->assign('default_slide', $default_slide);
        return view('', [
            '_page' => [
                'title' => '爱员工官网',
                'name' => $store_info['name']
            ]
        ]);
    }

    /**
     * 商家帮助指南
     */
    public function guide()
    {
        // 商家帮助指南分类列表
        $type_list = \Fields::getById('article');
        $guide_info = 0; // 商家帮助指南信息
        if (isset($type_list) && !empty($type_list)) {
            foreach ($type_list as $key => $val) {
                if ($val['tag'] == 'seller_guide') {
                    $guide_info = $val;
                    break;
                }
            }
            unset($type_list);
        }

        // 商家帮助指南分类下所有的的文章(包括商家帮助指南大类)
        $type_ids = $guide_info['id'] . ',';
        if (isset($guide_info['_child'])) {
            $type_ids .= implode(',', array_keys(reset_by_key($guide_info['_child'], 'id')));
        }
        $article_list = rpc('common/common/lists', [
            'article',
                [
                'isdelete' => 0,
                'status' => 1,
                'type_id' => [
                    'in',
                    $type_ids
                ]
            ]
        ]);
        $id = $this->request->param('article_id/d');
        $cate_id = $this->request->param('cate_id/d');
        if (!$id && $cate_id) {
            // 若有分类Id，则默认分类的第一篇文章
            $article = rpc('common/common/one', [
                'article',
                    [
                    'type_id' => $cate_id,
                    'isdelete' => 0,
                    'status' => 1
                ]
            ]);
        } elseif(!$id ){
            // 若从外链进来，不会有article_id，默认数据库第一条数据
            $id = $article_list[0]['id'];
            $article = $article_list[0];
        } else {
            // 文章内容
            $article = rpc('common/common/one', [
                'article',
                    [
                    'id' => $id,
                    'isdelete' => 0,
                    'status' => 1
                ]
            ]);
        }

        // 本文的分类名称
        $type_name = $guide_info['_child'][$article['type_id']]['name'];
        $this->view->assign('article_id', $id);
        $this->view->assign('article', $article);
        $this->view->assign('article_list', $article_list);
        $this->view->assign('type_name', $type_name);
        $this->view->assign('type_list', $guide_info['_child']);
        $this->assign('_page', [
            'title' => $article['title'].' - '.$type_name,
            'name' => '爱员工官网'
        ]);
        return $this->view->fetch();
    }

    /**
     * 商家开店申请
     */
    public function join()
    {
        if ($this->store_id > 0) { // 已经是商家，直接跳到商家管理页
            $this->redirect('seller/index/index');
            exit();
        }
        $this->assign('top_nav', 'joinin');
        return $this->view->fetch();
    }

    // 第1步：阅读协议
    public function step0()
    {
        $this->check_is_member();
        $this->assign('left_step', '0');
        $this->assign('top_nav', 'joinin');
        return view();
    }

    // 第2步：公司资质信息
    public function step1()
    {
        $this->check_is_member();
        $this->assign('left_step', '1');
        $this->assign('top_nav', 'joinin');
        return view();
    }

    // 第3步：财务资质信息
    public function step2()
    {
        $this->check_is_member();
        if ($this->request->isPost()) {
            $data = input('post.');
            $param = [];
            $param['member_name'] = $this->member_info['name'];
            $param['company_name'] = $data['company_name'];
            $param['company_area_code'] = intval($data['province_id']);
            $param['company_address'] = $data['company_address'];
            $param['company_address_detail'] = $data['company_address_detail'];
            $param['company_phone'] = $data['company_phone'];
            $param['company_employee_count'] = intval($data['company_employee_count']);
            $param['company_registered_capital'] = intval($data['company_registered_capital']);
            $param['contacts_name'] = $data['contacts_name'];
            $param['contacts_phone'] = $data['contacts_phone'];
            $param['contacts_email'] = $data['contacts_email'];
            $param['business_licence_number'] = $data['business_licence_number'];
            $param['business_licence_address'] = $data['business_licence_address'];
            $param['business_licence_start'] = $data['business_licence_start'];
            $param['business_licence_end'] = $data['business_licence_end'];
            $param['business_sphere'] = $data['business_sphere'];
            $param['organization_code'] = $data['organization_code'];

            $param['business_licence_number_electronic'] = $this->upload_pic_cookie('business_licence_number_electronic', '营业执照电子版');
            $param['general_taxpayer'] = $this->upload_pic_cookie('general_taxpayer', '一般纳税人证明');
            $param['organization_code_electronic'] = $this->upload_pic_cookie('organization_code_electronic', '组织机构代码证电子版');

            $this->step2_save_valid($param);

            $param['business_licence_start'] = date("Y-m-d", strtotime($param['business_licence_start']));
            $param['business_licence_end'] = date("Y-m-d", strtotime($param['business_licence_end']));
            if (!$this->joinInfo) {
                $param['member_id'] = $this->member_id;
                rpc('common/common/create', [
                    'store_joinin',
                    $param
                ]);
            } else {
                rpc('common/common/update', [
                    'store_joinin',
                        [
                        'member_id' => $this->member_id
                    ],
                    $param
                ]);
            }

            // 删除cookie记录的图片
            cookie(md5('store_pic_business_licence_number_electronic'), null);
            cookie(md5('store_pic_organization_code_electronic'), null);
            cookie(md5('store_pic_general_taxpayer'), null);
            return $this->redirect('index/store/step2');
        }

        $this->assign('left_step', '2');
        $this->assign('top_nav', 'joinin');
        return view();
    }

    // 店铺经营信息
    public function step3()
    {
        $this->check_is_member();
        if ($this->request->isPost()) {
            $data = input('post.');
            $param = [];
            $param['bank_account_name'] = $data['bank_account_name'];
            $param['bank_account_number'] = $data['bank_account_number'];
            $param['bank_name'] = $data['bank_name'];
            $param['bank_code'] = $data['bank_code'];
            $param['bank_address'] = $data['bank_address'];
            $param['bank_licence_electronic'] = $this->upload_pic_cookie('bank_licence_electronic', '开户银行许可证电子版');
            if (!empty($data['is_settlement_account'])) {
                $param['is_settlement_account'] = 1;
                $param['settlement_bank_account_name'] = $data['bank_account_name'];
                $param['settlement_bank_account_number'] = $data['bank_account_number'];
                $param['settlement_bank_name'] = $data['bank_name'];
                $param['settlement_bank_code'] = $data['bank_code'];
                $param['settlement_bank_address'] = $data['bank_address'];
            } else {
                $param['is_settlement_account'] = 2;
                $param['settlement_bank_account_name'] = $data['settlement_bank_account_name'];
                $param['settlement_bank_account_number'] = $data['settlement_bank_account_number'];
                $param['settlement_bank_name'] = $data['settlement_bank_name'];
                $param['settlement_bank_code'] = $data['settlement_bank_code'];
                $param['settlement_bank_address'] = $data['settlement_bank_address'];
            }
            $param['tax_registration_certificate'] = $data['tax_registration_certificate'];
            $param['taxpayer_id'] = $data['taxpayer_id'];
            $param['tax_registration_certificate_electronic'] = $this->upload_pic_cookie('tax_registration_certificate_electronic', '税务登记证号电子版');

            $this->step3_save_valid($param);
            rpc('common/common/update', ['store_joinin', ['member_id' => $this->member_id], $param]);
            return $this->redirect('index/store/step3');
        }

        $store_grade = \Fields::getById('store_grade');
        $this->assign('store_grade', $store_grade);

        $store_class = \Fields::getById('store_class');
        $this->assign('store_class', $store_class);

        $this->assign('left_step', '3');
        $this->assign('top_nav', 'joinin');
        return view();
    }

    // 合同签订及缴费
    public function step4()
    {
        if ($this->request->isPost()) {
            $store_class_ids = [];
            $store_class_names = [];
            $data = input('post.');
            $mallcate = config('mall_cate');

            $store_class_commis_rates = [];
            if (!empty($data['store_class_ids'])) {
                foreach ($data['store_class_ids'] as $value) {
                    $cate = array_filter(explode(',', $value));
                    $item = $mallcate[$cate[0]]['_child'][$cate[1]];
                    if ($item) {
                        $store_class_commis_rates[] = $item['commis_rate'];
                        $store_class_names[] = $mallcate[$cate[0]]['name'] . "," . $item['name'] . ",";
                        $store_class_ids[] = $cate[0] . "," . $cate[1] . ",";
                    }
                }
            }

            $param = [];
            $param['seller_name'] = $data['seller_name'];
            $param['store_name'] = $data['store_name'];
            $param['store_class_ids'] = serialize($store_class_ids);
            $param['store_class_names'] = serialize($store_class_names);
            $param['joinin_year'] = intval($data['joinin_year']) > 1 ? 2 : 1;
            $param['joinin_state'] = STORE_JOIN_STATE_NEW;
            $param['store_class_commis_rates'] = implode(',', $store_class_commis_rates);

            // 取店铺等级信息
            $grade_list = \Fields::getById('store_grade');
            $paying_amount = 0;
            $sg_id = $data['sg_id'];
            if (!empty($grade_list[$sg_id])) {
                $param['sg_id'] = $sg_id;
                $param['sg_name'] = $grade_list[$sg_id]['name'];
                $param['sg_info'] = serialize(array(
                    'sg_price' => $grade_list[$sg_id]['sg_price']
                ));
                $paying_amount += $grade_list[$sg_id]['sg_price'] * $param['joinin_year'];
            }

            // 取最新店铺分类信息
            $store_class_info = \Fields::getById('store_class');
            $sc_id = $data['sc_id'];
            if (isset($store_class_info[$sc_id])) {
                $param['sc_id'] = $sc_id;
                $param['sc_name'] = $store_class_info[$sc_id]['name'];
                $param['sc_bail'] = $store_class_info[$sc_id]['sc_bail'];
                $paying_amount += $param['sc_bail'];
            }

            // 店铺应付款
            $param['paying_amount'] = floatval($paying_amount);
            $this->step4_save_valid($param);

            rpc('common/common/update', ['store_joinin', ['member_id' => $this->member_id], $param]);
            return $this->redirect('index/store/step4');
        }

        $this->check_is_member();
        $this->joinInfo['store_class_ids'] = unserialize($this->joinInfo['store_class_ids']);
        $this->joinInfo['store_class_names'] = unserialize($this->joinInfo['store_class_names']);
        $this->joinInfo['store_class_commis_rates'] = explode(',', $this->joinInfo['store_class_commis_rates']);
        $this->joinInfo['sg_info'] = unserialize($this->joinInfo['sg_info']);
        $btn_next = false;
        $view = 'step4';
        switch ($this->joinInfo['joinin_state']) {
            case STORE_JOIN_STATE_NEW: // 入驻申请
                $step = 3;
                $message = '入驻申请已经提交，请等待管理员审核';
                break;
            case STORE_JOIN_STATE_VERIFY_FAIL: // 审核失败
                $step = 2;
                $btn_next = url('index/store/step1');
                $message = '审核失败:' . ($this->joinInfo['joinin_message'] ?: '请重新提交信息或者联系本站客服');
                $this->joinInfo = [];
                break;
            case STORE_JOIN_STATE_VERIFY_SUCCESS: // 初审成功，待支付
                if (!empty($this->joinInfo['sg_info'])) {
                    $store_grade_info = \Fields::getById('store_grade', $this->joinInfo['sg_id']);
                    $this->joinInfo['sg_price'] = $store_grade_info['sg_price'];
                } else {
                    $this->joinInfo['sg_info'] = @unserialize($this->joinInfo['sg_info']);
                    if (is_array($this->joinInfo['sg_info'])) {
                        $this->joinInfo['sg_price'] = $this->joinInfo['sg_info']['sg_price'];
                    }
                }
                $step = 4;
                $view = 'pay';
                $message = '';
                break;
            case STORE_JOIN_STATE_PAY_FAIL: // 支付审核失败
                $step = 2;
                $btn_next = false;
                $view = 'pay';
                $message = '付款审核失败:' . ($this->joinInfo['joinin_message'] ?: '请重新提交支付凭证或者联系本站客服');
                break;
            case STORE_JOIN_STATE_PAY: // 已支付
                $step = 4;
                $message = '已经提交，请等待管理员核对后为您开通店铺';
                $this->joinInfo = [];
                break;
        }

        $this->assign('joinin_detail', $this->joinInfo);
        $this->assign('left_step', 4);
        $this->assign('top_nav', 'joinin');
        return $this->show_join_message($message, $btn_next, $step, $view);
    }

    // 提交支付凭证
    public function pay()
    {
        $old = rpc('common/common/one', ['store_joinin', ['member_id' => $this->member_id]]);
        if (!$old) {
            return $this->error('请选完成公司资质信息填写', 'index/store/step0');
        } else if (!in_array($old['joinin_state'], [STORE_JOIN_STATE_VERIFY_SUCCESS, STORE_JOIN_STATE_PAY_FAIL])) {
            return $this->redirect('index/store/step4');
        }

        if ($this->request->isPost()) {
            $data = input('post.');
            $param = [];
            $param['paying_money_certificate'] = $this->upload_pic_cookie('paying_money_certificate', '付款凭证');
            $param['paying_money_certificate_explain'] = $data['paying_money_certificate_explain'];
            $param['joinin_state'] = STORE_JOIN_STATE_PAY;

            if (empty($param['paying_money_certificate'])) {
                return $this->error('请上传付款凭证');
            }

            rpc('common/common/update', ['store_joinin', ['member_id' => $this->member_id], $param]);
            return $this->redirect('index/store/step4');
        }
        return $this->redirect('index/store/step4');
    }

    /**
     * 根据当前状态显示入驻状态信息
     *
     * @param type $message
     * @param type $btn_next
     * @param type $step
     * @return type
     */
    private function show_join_message($message, $btn_next = FALSE, $step = '2', $sub_step = 'step4')
    {
        $this->assign('joinin_message', $message);
        $this->assign('btn_next', $btn_next);
        $this->assign('step', $step);
        $this->assign('sub_step', $sub_step);
        return view($sub_step);
    }

    // 检测卖家账号是否存在
    public function check_seller_name($seller_name = '')
    {
        $validate = new \think\Validate();
        $rule = [
            'seller_name|卖家账号' => 'require|alphaDash|length:1,50'
        ];

        $condition = [];
        $seller_name = $seller_name ?: input('get.seller_name');
        $condition['seller_name'] = $seller_name;

        if (!$validate->check($condition, $rule)) {
            return $validate->getError();
        }

        $store_count = rpc('common/common/total', ['seller', $condition]);

        $condition['member_id'] = ['neq', $this->member_id];
        $joinin_count = rpc('common/common/total', ['store_joinin', $condition]);

        $exist = $store_count > 0 || $joinin_count > 0;
        if ($this->request->isAjax()) {
            return $exist ? 'true' : 'false';
        }
        return $exist;
    }

    // 检测店铺名称是否存在
    public function check_store_name($store_name = '')
    {
        $condition = [];
        $store_name = $store_name ?: input('get.store_name');
        $condition['name'] = $store_name;
        $store_count = rpc('common/common/total', [
            'store',
            $condition
        ]);

        $condition = [];
        $condition['store_name'] = $store_name;
        $condition['member_id'] = [
            'neq',
            $this->member_id
        ];
        $joinin_count = rpc('common/common/total', [
            'store_joinin',
            $condition
        ]);

        $exist = $store_count > 0 || $joinin_count > 0;
        if ($this->request->isAjax()) {
            return $exist ? '店铺名称已存在' : 'true';
        }
        return $exist;
    }

    // 商铺列表
    public function lists()
    {
        // 店铺类目快速搜索
        $class_list = \Fields::getById("store_class");
        $s_cate_id = $this->request->param('cate_id/d', 0); // 店铺分类ID
        if (!key_exists($s_cate_id, $class_list)) {
            $s_cate_id = 0;
        }
        $s_keyword = $this->request->param('keyword/s', ''); // 关键字
        $s_areainfo = urldecode($this->request->param('area_info/s', '')); // 地区有携带空格，所以需要忽略掉url转换的空格符
        $s_order = $this->request->param('order/s', 'asc'); // desc倒序，asc顺序
        $s_key = $this->request->param('key/s', ''); // store_sales店铺销量，credit店铺信用
        $s_curpage = $this->request->param('curpage/d', 1); // store_sales店铺销量，credit店铺信用
        $s_limits = config('limit_store_list');
        if (empty($s_limits)) {
            $s_limits = 10; // 若没配置，默认10条
        }
        $condition = []; // 店铺搜索
        if (!empty($s_keyword)) {
            $condition['name|company_name'] = [
                'like',
                '%' . $s_keyword . '%'
            ];
        }
        if (!empty($s_areainfo)) {
            $condition['area_info'] = [
                'like',
                '%' . $s_areainfo . '%'
            ];
        }
        if ($s_cate_id > 0) {
            $condition['sc_id'] = $s_cate_id;
        }
        $condition['store_state'] = 1;
        if ($s_key && $s_order)
            $other['order'] = $s_key . ' ' . $s_order;
        else
            $other['order'] = ' sort asc ';
        $other['page'] = (($s_curpage - 1) * $s_limits) . ',' . $s_limits;
        $other['field'] = 'id as store_id,name,member_id,member_name,seller_name,sc_id,company_name,areacode,area_info,address,store_state,label,store_sales,credit';
        $store_list = $this->db_lists('store', $condition, $other);
        $total_num = rpc('common/common/total', [
            'store',
            $condition
        ]);
        // 排序生成url用
        $query = [
            'key' => $s_key,
            'order' => $s_order,
            'cate_id' => $s_cate_id,
            'keyword' => $s_keyword,
            'area_info' => $s_areainfo
        ];
        // 分页渲染内容
        $option = [
            'var_page' => 'curpage',
            'path' => '/index/store/lists',
            'query' => $query
        ];
        $page = \Page::make($store_list, $s_limits, $s_curpage, $total_num, false, $option);
        // 获取店铺商品数，推荐商品列表等信息
        $store_list = model('Common/Store')->getStoreSearchList($store_list);
        // 当前位置
        if ($s_cate_id > 0 && key_exists($s_cate_id, $class_list)) {
            $nav_link[1]['link'] = url('index/store/lists');
            $nav_link[1]['title'] = '店铺';
            $nav = $class_list[$s_cate_id]['name'];
            // 存入当前级
            $nav_link[2]['title'] = $nav;
        } else {
            $nav_link[1]['link'] = config('url_base');
            $nav_link[1]['title'] = '首页';
            $nav_link[2]['title'] = '店铺';
        }
        $this->view->assign('nav_link', $nav_link);
        $this->view->assign('purl', url('index/store/lists', $this->request->get()));
        $this->view->assign('keyword', $s_keyword);
        $this->view->assign('cate_id', $s_cate_id);
        $this->view->assign('cate_name', $class_list[$s_cate_id]['sc_name']);
        $this->view->assign('s_key', $s_key);
        $this->view->assign('s_order', $s_order);
        $this->view->assign('s_areainfo', $s_areainfo);
        $this->view->assign('class_list', $class_list);
        $this->view->assign('store_list', $store_list);
        $this->view->assign('total_num', $total_num);
        $this->view->assign('page', $page);
        // SEO
        $this->view->assign('_page', [
            'title' => '爱员工官网搜索',
            'name' => $s_keyword
        ]);
        return $this->view->fetch();
    }

    // 分类选择器
    public function json_class()
    {
        $id = request()->get('gc_id/d');
        $goodsClass = config('mall_cate');
        if (!isset($goodsClass[$id])) {
            exit('');
        }
        if (isset($goodsClass[$id]) && is_array($goodsClass[$id]) && isset($goodsClass[$id]['_child']) && is_array($goodsClass[$id]['_child'])) {
            $goodsClass = $goodsClass[$id]['_child'];
        }
        $array = [];
        if (is_array($goodsClass) && count($goodsClass) > 0) {
            foreach ($goodsClass as $val) {
                $array[$val['id']] = [
                    'gc_id' => $val['id'],
                    'gc_name' => htmlspecialchars($val['name']),
                    'gc_parent_id' => $val['pid'],
                    'commis_rate' => $val['commis_rate'],
                    'gc_sort' => $val['sort']
                ];
            }
        }

        $array = array_values($array);

        return jsonp($array);
    }

    // 上传证书，并缓存路径到cookie，出错时，直接使用已经上传成功的旧图
    protected function upload_pic_cookie($name, $tip = '')
    {
        $file = $this->uploadFile($name, 'joinin');
        $cookie = md5('store_pic_' . $name);
        if ($file['status']) {
            $path = $file['save_path_type'] . $file['save_name'];
            $old = str_replace("..", '', cookie($cookie)); // 防止伪造路径
            if ($old && is_file(ROOT_PATH . 'public/uploads/' . $old)) {
                // 删除旧图片
                @unlink(ROOT_PATH . 'public/uploads/' . $old);
            }
            cookie($cookie, $path);
        } else {
            $path = cookie($cookie);
            if (!$path) {
                $this->error($tip . '上传失败：' . $file['error'] ?: "未知错误");
            }
        }

        return $path;
    }

    /**
     * Step2 检验数据
     *
     * @param type $param
     */
    private function step2_save_valid($param)
    {
        $validate = new \think\Validate();
        $rule = [
            'company_name|公司名称' => 'require|length:1,50',
            'company_address|公司地址' => 'require|length:1,50',
            'company_address_detail|公司详细地址' => 'require|length:1,50',
            'company_phone|公司电话' => 'require|length:1,20',
            'company_employee_count|员工总数' => 'require|number|length:1,10',
            'company_registered_capital|注册资金' => 'require|number|length:1,10',
            'contacts_name|联系人姓名' => 'require|length:1,20',
            'contacts_phone|联系人电话' => 'require|length:1,20',
            'contacts_email|电子邮箱' => 'require|email|length:1,50',
            'business_licence_number|营业执照号' => 'require|length:1,20',
            'business_licence_address|营业执照所在地' => 'require|length:1,50',
            'business_licence_start|营业执照有效期' => 'require|length:1,20',
            'business_licence_end|营业执照有效期' => 'require|length:1,20',
            'business_sphere|法定经营范围' => 'require|length:1,200',
            'business_licence_number_electronic|营业执照电子版' => 'require',
            'organization_code|组织机构代码' => 'require|length:1,20',
            'organization_code_electronic|组织机构代码电子版' => 'require'
        ];

        if (!$validate->check($param, $rule)) {
            $this->error($validate->getError());
        }
    }

    /**
     * Step3 检验数据
     *
     * @param type $param
     */
    private function step3_save_valid($param)
    {
        $validate = new \think\Validate();
        $rule = [
            'bank_account_name|银行开户名' => 'require|length:1,50',
            'bank_account_number|银行账号' => 'require|length:1,20',
            'bank_name|开户银行支行名称' => 'require|length:1,50',
            'bank_code|支行联行号' => 'require|length:1,20',
            'bank_address|开户行所在地' => 'require|length:1,100',
            'bank_licence_electronic|开户银行许可证电子版' => 'require',
            'settlement_bank_account_name|银行开户名' => 'require|length:1,50',
            'settlement_bank_account_number|银行账号' => 'require|length:1,20',
            'settlement_bank_name|开户银行支行名称' => 'require|length:1,50',
            'settlement_bank_code|支行联行号' => 'require|length:1,30',
            'settlement_bank_address|开户行所在地' => 'require|length:1,100',
            'tax_registration_certificate|税务登记证号' => 'require|length:1,20',
            'taxpayer_id|纳税人识别号' => 'require|length:1,20',
            'tax_registration_certificate_electronic|税务登记证号电子版' => 'require'
        ];

        if (!$validate->check($param, $rule)) {
            $this->error($validate->getError());
        }
    }

    /**
     * Step4 检验数据
     *
     * @param type $param
     */
    private function step4_save_valid($param)
    {
        $validate = new \think\Validate();

        $rule = [
            'store_name|店铺名称' => 'require|length:1,50',
            'sg_id|店铺等级' => 'require',
            'sc_id|店铺分类' => 'require'
        ];

        if (!$validate->check($param, $rule)) {
            $this->error($validate->getError());
        }
    }

    // 检查当前登录
    protected function check_is_member()
    {
        if ($this->member_id < 1) { // 未登录的先登录
            $this->redirect('index/store/join');
            exit();
        } else
        if ($this->store_id > 0) { // 已经是商家，直接跳到商家管理页
            $this->redirect('seller/index/index');
            exit();
        } else {
            $action = $this->request->action();
            $this->joinInfo = rpc('common/common/one', [
                'store_joinin',
                    [
                    'member_id' => $this->member_id
                ]
            ]);
            if ($this->joinInfo) {
                if ($this->joinInfo['joinin_state'] > 0) {
                    if (!in_array($action, [
                                'step4'
                            ]) && $this->joinInfo['joinin_state'] != STORE_JOIN_STATE_VERIFY_FAIL) {
                        $this->redirect('index/store/step4');
                    }
                } else {
                    if (in_array($action, [
                                'step4'
                            ])) {
                        $this->redirect('index/store/step0');
                    }
                }
            } else
            if (in_array($action, [
                        'step3',
                        'step4'
                    ])) {
                $this->error('请选完成公司资质信息填写', 'index/store/step0');
            }
        }
    }

}
